package com.lottery.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lottery.dto.MachinesOutputDTO;
import com.lottery.pojo.TableMachines;
import com.lottery.service.MachineService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MachineController {

    @Autowired
    private MachineService machineService;

    @PostMapping("addOrUpdateMachine")
    public void addOrUpdateMachine(String machine_number, String password) {
        machineService.addOrUpdateMachine(machine_number, password);
    }

    @PostMapping("deleteMachine")
    public void deleteMachine(int id) {
        machineService.deleteMachine(id);
    }

    @PostMapping("getMachines")
    public MachinesOutputDTO getMachines(//分页
                                         @RequestParam(name = "page", required = false, defaultValue = "0") int page,
                                         @RequestParam(name = "pageSize", required = false, defaultValue = "0") int pageSize) {
        PageHelper.startPage(page, pageSize);
        PageInfo<TableMachines> pageInfo = new PageInfo<>(machineService.getMachines(null));
        MachinesOutputDTO outputDTO = new MachinesOutputDTO();
        outputDTO.setMachineList(pageInfo.getList());

        int offlineCount = (int) pageInfo.getList().stream().filter(tableMachines -> tableMachines.getIs_online() == 0).count();
        outputDTO.setOfflineCount(offlineCount);
        outputDTO.setOnlineCount(pageInfo.getList().size() - offlineCount);
        outputDTO.setPageCount(pageInfo.getPages());
        return outputDTO;
    }

    /**更新machine的提成比例*/
    @PostMapping("updateMachineCommission")
    public void updateMachineCommission(String machine_number, String commission) {
        machineService.updateMachineCommission(machine_number, commission);
    }
}
